package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.messageprocessors.ResponseProcessorImp;

import java.util.Date;
import java.util.concurrent.BlockingQueue;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressType;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressValue;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.WriteCoilRequest;
import net.wimpi.modbus.msg.WriteCoilResponse;
import net.wimpi.modbus.procimg.SimpleDigitalOut;

public class WriteCoilResponseProcessor extends AbstractResponseProcessor {
	
	private static final Integer INT_1 = new Integer(1);
	private static final Integer INT_0 = new Integer(0);

	@Override
	public void processResponse(ModbusRequest req, ModbusResponse res, BlockingQueue<AddressValue> queue) {
		// TODO WriteCoilResponseProcessor error IllegalAddressException
		if(res instanceof WriteCoilResponse && req instanceof WriteCoilRequest){
			
			boolean bit = ((WriteCoilResponse) res).getCoil();
			int reference = ((WriteCoilResponse)res).getReference();
			Date date = new Date();

			AddressValue newValue = new AddressValue();
			newValue.setAddress(reference);
			newValue.setAddressType(AddressType.COIL);
			newValue.setDate(date);
			if(bit)
			   newValue.setValue(INT_1);
			else
			   newValue.setValue(INT_0);
			
			queue.add(newValue);
			
			getImage().setDigitalOut(reference,new SimpleDigitalOut(bit),date);
			
			/*
			if( getDeciveDAO() != null )
				if(bit)
					getDeciveDAO().saveValue( getDevice(), reference ,INT_1 , AddressType.COIL );
				else
					getDeciveDAO().saveValue( getDevice(), reference ,INT_0 , AddressType.COIL );
			*/
		}
	}

}
